package com.hctforgreen.greenservice;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.model.LoginResultEntity;
import com.hctforgreen.greenservice.model.StaffRoleEntity;
import com.hctforgreen.greenservice.utils.ContantsUtil;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.HttpUtil;
import com.hctforgreen.greenservice.utils.LoginResultStoreUtil;
import com.hctforgreen.greenservice.utils.MachineCodeUtil;
import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;
import java.util.Map;

/**
 * 培训页面
 *
 * @author Dhb
 */
public class TrainActivity extends ParentActivity implements OnClickListener {
    private static final String TAG = "TrainActivity";

    /**
     * 是否是派工跳转过掌上通
     */
    private boolean isDispatching = false;
    /**
     * 登录标识，用于判断登录掌上通正式服务器的次数，超过1次则判断为正式服务器宕机
     */
    public int pingCount = 0;

    private Bundle loginBundle;//记录登陆接口传回来的参数

    //用于标记是否是从派工跳转过来的 true是从派工跳转过来的
    public boolean isGREEDAQ;
    public static Handler sHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_train);

        initIntent();
        initTitleButtonBar();
        initSkinLayout();
        initWindow();
        loginWithDispatch();
        initHandler();
        initStaffRole();
    }

    private void initIntent() {
        boolean loc = getIntent().getBooleanExtra("loc", false);
        int pingCount = getIntent().getIntExtra("PING_COUNT", 0);
        boolean isCloudServer = getIntent().getBooleanExtra("WHICH_SERVER", false);
        String phone = getIntent().getStringExtra("phone");
        Log.d(TAG, "loc = " + loc + "，pingCount = " + pingCount + "，isCloudServer = " + isCloudServer + "，phone = " + phone);
        if (!TextUtils.isEmpty(phone) && phone.trim().length() == 11) {
            ContantsUtil.sPhoneNumber = phone;
        }
    }

    private void loginWithDispatch() {
        //增加派工系统跳转到该activity
        MachineCodeUtil codeUtil = new MachineCodeUtil(TrainActivity.this);
        if (getIntent().getStringExtra("phone") != null) {
            //2017.11.01--390694增加派工工程名判断
            isDispatching = true;
            doLoginin(getIntent().getStringExtra("phone"), codeUtil.getMachineCode(), codeUtil.getIMEICode());
        }
    }

    private void initStaffRole() {
        final String url = HctConstants.NET_URL + "token-person-mobile!getAppRoleByPhone.do";
        final Map<String, String> map = new HashMap<>();
        map.put("phone", ContantsUtil.sPhoneNumber);
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (!TextUtils.isEmpty(ContantsUtil.sStaffRole)) {
                    return;
                }
                String jsonString = HttpUtil.getInstance().getAppRoleByPhone(url, map, "getStaffType");
                StaffRoleEntity entity = HttpUtil.getInstance().parseStaffRole(jsonString);
                sHandler.sendMessage(sHandler.obtainMessage(0, entity));
            }
        }).start();
    }

    @SuppressLint("HandlerLeak")
    private void initHandler() {
        sHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0:
                        StaffRoleEntity entity = (StaffRoleEntity) msg.obj;
                        if (null == entity) {
                            return;
                        }
                        if (entity.getErrorCode() == 200) {
                            ContantsUtil.sStaffRole = entity.getStaffWorkType();
                            ContantsUtil.initRolePosition();
                        } else if (entity.getErrorCode() == 401) {
                            ContantsUtil.sStaffRole = null;
                        }
                        break;
                    default:
                        break;
                }
            }
        };
    }

    /**
     * 派工系统调入登陆 390694 2017/11/01
     */
    private void doLoginin(final String phone, final String onlyCode, final String imeiCode) {
        MobclickAgent.onEvent(this, "Account_login");
        /**
         * 2017 11 01 390694
         * 修改友盟jar
         *
         * 去除MobclickAgent.onEventBegin(this, "Account_login");
         * MobclickAgent.onEventEnd(LoginActivity.this, "Account_login");
         * 该方法废除
         * 统计登录时间，需要自己去获取经历的时间，然后将其传出
         */
        //获取当前时间的毫秒值
        final long firstTime = System.currentTimeMillis();

        @SuppressLint("HandlerLeak") final Handler handler = new Handler() {
            public void handleMessage(Message msg) {

                //登陆之后的毫秒值
                long secondTime = System.currentTimeMillis();
                int time = (int) (secondTime - firstTime);
//				使用该方法将时间传给友盟统计
                MobclickAgent.onEventValue(TrainActivity.this, "Account_login", null, time);
                HctResult hctResult = new HctResult();
                /*2016.3.9号之前所注释的代码位置如下，2016.3.9修改为放置在case HctConstants.STATUS_SUCCESS里
                 * hctResult = (HctResult) msg.obj;
				LoginResultEntity entity = (LoginResultEntity) hctResult.data;
				entity.phone = phone;*/
                switch (msg.what) {
                    case HctConstants.STATUS_SUCCESS:
                        hctResult = (HctResult) msg.obj;
                        LoginResultEntity entity = (LoginResultEntity) hctResult.data;
                        ContantsUtil.sPersonId = entity.personId;
                        entity.phone = phone;
                        if (entity.loginStatus.equals("0")) {//正常登陆
                            if (getIntent().getExtras() != null) {
                                loginBundle = getIntent().getExtras();//记录登陆接口传回来的参数，在重新打开主界面时可以调用
                                //add 390697 用于保存是否从派工跳转过来的 机型提示中使用
                                if (loginBundle != null) {
                                    isGREEDAQ = true;
                                }
                            }
                            String fun = entity.functions;
                            if (entity.functions.contains("!16!")) {// 有售后培训权限
                                LoginResultStoreUtil.save(TrainActivity.this, entity);// 保存用户信息
                                return;
                            } else {// 无售后培训权限时，重新登陆
                                Toast.makeText(TrainActivity.this, phone + getString(R.string.auto_login_notrain_warn), Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent();
                                intent.setClass(TrainActivity.this, LoginActivity.class);
                                intent.putExtra("phone", phone);
                                intent.putExtra("isDispatching", isDispatching);
                                startActivity(intent);
                                finish();
                            }

                        } else {
                            Toast.makeText(TrainActivity.this, getString(R.string.auto_login_warn), Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent();
                            intent.setClass(TrainActivity.this, LoginActivity.class);
                            intent.putExtra("phone", phone);
                        /*390694--2016.5.26添加
                         *是否是派工跳转的值传给登录界面
						 */
                            intent.putExtra("isDispatching", isDispatching);
                            startActivity(intent);
                            finish();
                        }
                        break;

                    case HctConstants.STATUS_FAILD:
                        Toast.makeText(TrainActivity.this, getString(R.string.auto_login_warn), Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent();
                        intent.setClass(TrainActivity.this, LoginActivity.class);
                        intent.putExtra("phone", phone);
                    /*390694--2016.5.26添加
                     *是否是派工跳转的值传给登录界面
					 */
                        intent.putExtra("isDispatching", isDispatching);
                        startActivity(intent);
                        finish();
                        break;
                }
            }
        };

        new Thread() {
            public void run() {
                Message message = new Message();
                try {
                    HctController controller = new HctController(TrainActivity.this);
                    HctResult result = controller.appLogin(phone, onlyCode, imeiCode, "", "", pingCount);
                    if (result.status == HctConstants.STATUS_SUCCESS) {
                        message.what = result.status;
                        message.obj = result;
                    } else {
                        message.what = HctConstants.STATUS_FAILD;
                    }
                } catch (Exception e) {
                    message.what = HctConstants.STATUS_FAILD;
                    e.printStackTrace();
                }
                handler.sendMessage(message);
            }
        }.start();
    }

    private void initTitleButtonBar() {
        final TextView titleTv = (TextView) findViewById(R.id.tv_title);
        titleTv.setText(getString(R.string.activity_train_title));

        final ImageButton backBtn = (ImageButton) findViewById(R.id.btn_back);
        backBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initWindow() {

        findViewById(R.id.lyt_learning_materials).setOnClickListener(this);// 学习资料
        findViewById(R.id.lyt_servey).setOnClickListener(this);// 调研
        findViewById(R.id.lyt_information_interaction).setOnClickListener(this);// 信息交互
        findViewById(R.id.lyt_examine).setOnClickListener(this);// 考试
        findViewById(R.id.lyt_new_training).setOnClickListener(this);//新学员培训
        findViewById(R.id.lyt_new_staff_learning_result).setOnClickListener(this);//新员工资质学习与验收
        // initThemeSettingLayout();
        // initLanguageSetting();
        // initAboutUsLayout();
        // initQrcodeDownloadLayout();
        // initSupportMidLayout();
        // initAddFeedLayout();
        // initUpgradeDescription();
        // initVersionUpdateLayout();
        // initClearCacheLayout();
        // initLoginOutLayout();
        // initDownLoadStoreLayout();
        // initWifiFreshState();
        // initPointsRule();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lyt_learning_materials:// 学习资料
                Intent intent = new Intent(TrainActivity.this,
                        LearningActivity.class);
                startActivity(intent);
                break;
            case R.id.lyt_examine:// 考试
                intent = new Intent(TrainActivity.this, ExamSearchActivity.class);
                startActivity(intent);

                break;
            case R.id.lyt_new_training:// 新学员培训
                intent = new Intent(TrainActivity.this, NewStudentTrainActivity.class);
                intent.putExtra("studyTypeId", "");
                intent.putExtra("personId", "");
                String childtypeId = "";
                intent.putExtra("childtypeId", childtypeId);
                intent.putExtra("searchKey", "");
                startActivity(intent);
                break;
            case R.id.lyt_servey:// 调研
                break;
            case R.id.lyt_information_interaction:// 信息交互
                break;
            case R.id.lyt_new_staff_learning_result://新员工资质学习与验收
                AfterSalesLearningResultActivity.launch(this);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //如果该Activity销毁的时候，正在执行网络请求则取消
        HttpUtil.getInstance().cancelGetUserTypeRequest();
    }
}
